package epidemic

import (
	"encoding/json"
	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/model/common/request"
	response "gitee.com/baal1990/epidemic/model/common/response_dfitc"
	"gitee.com/baal1990/epidemic/model/epidemic"
	epidemicReq "gitee.com/baal1990/epidemic/model/epidemic/request"
	epidemicRsp "gitee.com/baal1990/epidemic/model/epidemic/response"
	"gitee.com/baal1990/epidemic/service"
	"gitee.com/baal1990/epidemic/utils/validator"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strings"
	"time"
)

type EpidemicInvestigationFormApi struct {
}

var epidemicInvestigationFormService = service.ServiceGroupApp.EpidemicServiceGroup.EpidemicInvestigationFormService

// CreateEpidemicInvestigationForm 创建EpidemicInvestigationForm
// @Tags EpidemicInvestigationForm
// @Summary 创建EpidemicInvestigationForm
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body epidemic.EpidemicInvestigationForm true "创建EpidemicInvestigationForm"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /epidemicInvestigationForm/createEpidemicInvestigationForm [post]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) CreateEpidemicInvestigationForm(c *gin.Context) {
	var epidemicInvestigationForm epidemic.EpidemicInvestigationForm
	_ = c.ShouldBindJSON(&epidemicInvestigationForm)
	if err := epidemicInvestigationFormService.CreateEpidemicInvestigationForm(epidemicInvestigationForm); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteEpidemicInvestigationForm 删除EpidemicInvestigationForm
// @Tags EpidemicInvestigationForm
// @Summary 删除EpidemicInvestigationForm
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body epidemic.EpidemicInvestigationForm true "删除EpidemicInvestigationForm"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /epidemicInvestigationForm/deleteEpidemicInvestigationForm [delete]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) DeleteEpidemicInvestigationForm(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		global.GVA_LOG.Error("参数错误!id 为 0!!!")
		response.FailWithMessage("参数错误", c)
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", id))
	if err := epidemicInvestigationFormService.DeleteEpidemicInvestigationForm(id); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteEpidemicInvestigationFormByIds 批量删除EpidemicInvestigationForm
// @Tags EpidemicInvestigationForm
// @Summary 批量删除EpidemicInvestigationForm
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除EpidemicInvestigationForm"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /epidemicInvestigationForm/deleteEpidemicInvestigationFormByIds [delete]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) DeleteEpidemicInvestigationFormByIds(c *gin.Context) {
	var IDS request.IdsReq
	_ = c.ShouldBindJSON(&IDS)
	global.GVA_LOG.Info("请求参数", zap.Any("param", IDS))
	if err := epidemicInvestigationFormService.DeleteEpidemicInvestigationFormByIds(IDS); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// FindEpidemicInvestigationForm 用id查询EpidemicInvestigationForm
// @Tags EpidemicInvestigationForm
// @Summary 用id查询EpidemicInvestigationForm
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query epidemic.EpidemicInvestigationForm true "用id查询EpidemicInvestigationForm"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /epidemicInvestigationForm/findEpidemicInvestigationForm [get]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) FindEpidemicInvestigationForm(c *gin.Context) {
	var epidemicInvestigationForm epidemic.EpidemicInvestigationForm
	_ = c.ShouldBindQuery(&epidemicInvestigationForm)
	global.GVA_LOG.Info("请求参数", zap.Any("param", epidemicInvestigationForm))
	if reepidemicInvestigationForm, err := epidemicInvestigationFormService.GetEpidemicInvestigationForm(epidemicInvestigationForm.ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"reepidemicInvestigationForm": reepidemicInvestigationForm}, c)
	}
}

// GetEpidemicInvestigationFormList 分页获取EpidemicInvestigationForm列表
// @Tags EpidemicInvestigationForm
// @Summary 分页获取EpidemicInvestigationForm列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query epidemicReq.EpidemicInvestigationFormSearch true "分页获取EpidemicInvestigationForm列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /epidemicInvestigationForm/getEpidemicInvestigationFormList [get]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) GetEpidemicInvestigationFormList(c *gin.Context) {
	var pageInfo epidemicReq.EpidemicInvestigationFormSearch
	epidemicUser := c.MustGet("OPERATION_USER_INFO").(epidemic.EpidemicUser)
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage("参数错误："+err.Error(), c)
		return
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", pageInfo))
	if list, total, err := epidemicInvestigationFormService.GetEpidemicInvestigationFormInfoList(pageInfo, epidemicUser); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// 用户侧
// 获取疫情排查表分页列表
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) GetEpidemicInvestigationFormListUserSide(c *gin.Context) {
	curUser := c.MustGet("OPERATION_USER_INFO").(epidemic.EpidemicUser)
	var pageInfo epidemicReq.EpidemicInvestigationFormListUserSide
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage("参数错误："+err.Error(), c)
		return
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", pageInfo))
	if list, total, err := epidemicInvestigationFormService.GetEpidemicInvestigationFormInfoListUserSide(pageInfo, curUser.Mobile); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		// 构造应答结构
		var listRsp []epidemicRsp.EpidemicInvestigationFormListUserSide
		for _, e := range list {
			questions, err := genQuestionsForApp(e)
			if err != nil {
				global.GVA_LOG.Error("解析问题列表失败!", zap.Error(err))
				response.FailWithMessage("服务器内部错误", c)
				return
			}
			var link string
			if e.Link != "" {
				link = global.GVA_CONFIG.System.AccessHost + "file/" + e.Link
			}
			listRsp = append(listRsp, epidemicRsp.EpidemicInvestigationFormListUserSide{
				Id:               int(e.ID),
				Title:            e.Title,
				Content:          e.Content,
				Link:             link,
				Questions:        questions,
				Status:           e.Status,
				Answer:           e.Answer,
				SpecialSituation: e.SpecialSituation,
				UrlLink:          e.UrlLink,
			})
		}
		response.OkWithDetailed(response.PageResult{
			List:     listRsp,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// 用户侧
// 疫情排查表填报
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) GetEpidemicInvestigationFormCheckinUserSide(c *gin.Context) {
	var req epidemicReq.EpidemicInvestigationFormCheckinUserSide
	if err := c.ShouldBind(&req); err != nil {
		global.GVA_LOG.Error("参数错误!", zap.Error(err))
		response.FailWithMessage("参数错误", c)
		return
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", req))
	curUser := c.MustGet("OPERATION_USER_INFO").(epidemic.EpidemicUser)
	// 从登录用户获取手机号
	req.Mobile = curUser.Mobile
	if err := epidemicInvestigationFormService.EpidemicInvestigationFormCheckinUserSide(req); err != nil {
		global.GVA_LOG.Error("操作失败!", zap.Error(err))
		response.FailWithMessage("操作失败", c)
	} else {
		response.Ok(c)
	}
}

// 生成问题列表
// 以逗号分隔，app不需要判定标准
func genQuestionsForApp(e epidemic.EpidemicInvestigation) (string, error) {
	var result []string
	var questions epidemicRsp.EpidemicInvestigationFormQuestions
	if err := json.Unmarshal([]byte(e.Questions), &questions); err != nil {
		return "", err
	}
	for _, e := range questions.Questions {
		result = append(result, e.Question)
	}
	return strings.Join(result, ","), nil
}

// UpdateEpidemicInvestigationForm 更新EpidemicInvestigationForm
// @Tags EpidemicInvestigationForm
// @Summary 更新EpidemicInvestigationForm
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body epidemic.EpidemicInvestigationForm true "更新EpidemicInvestigationForm"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /epidemicInvestigationForm/updateEpidemicInvestigationForm [put]
func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) UpdateEpidemicInvestigationForm(c *gin.Context) {
	var req epidemicReq.EpidemicInvestigationFormUpdateStatus
	err := c.ShouldBind(&req)
	if err != nil {
		response.FailWithMessage("参数错误："+err.Error(), c)
		return
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", req))
	if err := epidemicInvestigationFormService.UpdateStatus(req); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

func (epidemicInvestigationFormApi *EpidemicInvestigationFormApi) CreateOrUpdate(c *gin.Context) {
	var req epidemic.EpidemicInvestigationForm
	err := c.ShouldBind(&req)
	if err != nil {
		response.FailWithMessage("参数错误："+err.Error(), c)
		return
	}
	global.GVA_LOG.Info("请求参数", zap.Any("param", req))
	operaterUser := c.MustGet("OPERATION_USER_INFO").(epidemic.EpidemicUser)
	//非超级管理员编辑时候判断
	if operaterUser.Role != global.DICT_ROLES_SUPER {
		if operaterUser.Company != req.Company ||
			!validator.ValidateDepartment(operaterUser.Department, req.Department) {
			response.FailWithMessage("账号权限不足", c)
			return
		}
	}
	questions := epidemicRsp.EpidemicInvestigationFormQuestions{}
	if err := json.Unmarshal([]byte(req.Questions), &questions); err != nil {
		response.FailWithMessage("参数错误："+err.Error(), c)
		return
	}
	if req.ID == 0 {
		req.PublishedBy = operaterUser.Name
		req.PublishDate = time.Now().Format("2006/01/02 15:04:05.000")
		if req.Status == "" {
			req.Status = global.DICT_INVESTIGATION_FORM_STATUS_OPEN
		}
		if err := epidemicInvestigationFormService.CreateEpidemicInvestigationForm(req); err != nil {
			global.GVA_LOG.Error("创建失败!", zap.Error(err))
			response.FailWithMessage("创建失败", c)
		} else {
			response.OkWithMessage("创建成功", c)
		}
	} else {
		if err := epidemicInvestigationFormService.UpdateEpidemicInvestigationForm(req); err != nil {
			global.GVA_LOG.Error("更新失败!", zap.Error(err))
			response.FailWithMessage("更新失败", c)
		} else {
			response.OkWithMessage("更新成功", c)
		}
	}

}
